package com.wangtao.firstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.adapters.BaskCommentAdapter;
import com.wangtao.firstapp.custom.FullyLinearLayoutManager;
import com.wangtao.firstapp.custom.ScRecyclerView;
import com.wangtao.firstapp.modles.BaskDetailsData;
import com.wangtao.firstapp.utils.DialogUtils;
import com.wangtao.firstapp.utils.HttpUtils;
import com.wangtao.firstapp.utils.ToastUtils;

import org.xutils.common.util.DensityUtil;
import org.xutils.image.ImageOptions;
import org.xutils.x;

/**
 * 晒单详情页面
 * Created by lanouhn on 16/9/12.
 */
public class BaskDetailsActivity extends Activity implements View.OnClickListener {

    //用于存作者Id
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    //布局中控件对象
    private ImageButton back, likes_iv, imageview;
    private ImageView logo, myLogo, iv_shop;
    private TextView name, attention, content, likes, tv_title1, item_name, price, likes_tv, textView, comments;
    private LinearLayout lltImageBig, lltShop,lltFoot;
    private ScRecyclerView comments_ScRecyclerView;
    private EditText mySpeak;
    private RelativeLayout re, rltLikes;

    //实体类对象
    private BaskDetailsData baskDetailsData;
    //评论
    private BaskCommentAdapter baskCommentAdapter;

    // 点击事件标志位
    private int flag = 0;

    //创建自定义Dialog对象，并实例化
    DialogUtils dialogUtils = new DialogUtils(BaskDetailsActivity.this);

    //创建自定义Toast，并实例化
    ToastUtils toastUtils = new ToastUtils(BaskDetailsActivity.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_baskdetails);
        initView();
        getDataFromWeb();
        initEvent();
    }

    private void initView() {
        back = (ImageButton) findViewById(R.id.back_act_baskdetails);//返回上一个页面
        logo = (ImageView) findViewById(R.id.logo_act_baskdetails);//作者头像
        name = (TextView) findViewById(R.id.name_act_baskdetails);//作者昵称
        attention = (TextView) findViewById(R.id.attention_act_baskdetails);//关注，点击后变为“已关注”，背景为灰色。二次点击之后，恢复原样
        lltImageBig = (LinearLayout) findViewById(R.id.lltImageBig_act_baskdetails);//用于动态加载大图用的LinearLayout
        content = (TextView) findViewById(R.id.content_act_baskdetails);//主内容，纯文字
        likes = (TextView) findViewById(R.id.likes_act_baskdetails);//...人喜欢
        comments_ScRecyclerView = (ScRecyclerView) findViewById(R.id.comments_ScRecyclerView_act_baskdetails);//用于加载评论区列表
        myLogo = (ImageView) findViewById(R.id.myLogo_act_baskdetails);//我的头像
        mySpeak = (EditText) findViewById(R.id.mySpeak_act_baskdetails);//我要评论，，，

        re = (RelativeLayout) findViewById(R.id.re_sife_second_view_one);//容器，点击之后进入 单品详情页面
        iv_shop = (ImageView) findViewById(R.id.iv_shop);//卖东西处商品图片
        tv_title1 = (TextView) findViewById(R.id.tv_title1);//卖东西处商品 品牌
        item_name = (TextView) findViewById(R.id.item_name_sife_second_view_one);//卖东西处商品名称
        price = (TextView) findViewById(R.id.price_name_sife_second_view_one);//卖东西处的商品价格
        //点击rltLikes，切换视图
        rltLikes = (RelativeLayout) findViewById(R.id.rltLikes_sife_second_view_one);//卖东西处的“喜欢”，，容器
        //点击点击rltLikes之 前 显示
        likes_iv = (ImageButton) findViewById(R.id.likes_iv_sife_second_view);//卖东西处 灰色的心
        likes_tv = (TextView) findViewById(R.id.likes_tv_sife_second_view);//卖东西处 跟在灰色的心后边显示，。要设置为“喜欢”
        //点击点击rltLikes之 后 显示
        imageview = (ImageButton) findViewById(R.id.imageview_toast_like);//卖东西处 红色的心
        textView = (TextView) findViewById(R.id.textView_sife_second_view_one);//卖东西处 跟在灰红色的心后边显示

        lltShop = (LinearLayout) findViewById(R.id.lltShop_sife_second_view_one);//购买的容器，点击购买
        comments = (TextView) findViewById(R.id.comments_act_baskdetails);//"查看 全部？条评论"
        lltFoot= (LinearLayout) findViewById(R.id.lltFoot_act_baskdetails);//最下部，放置“自己头像，我要讲两句” 的容器

        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        editor = sp.edit();
    }

    private void getDataFromWeb() {
        Intent intent = getIntent();
        String baskdetails_ID = intent.getStringExtra("baskdetails_iD");

        String urlBaskDetails = "http://open4.bantangapp.com/community/post/info";
        String paramsBaskDetails = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2573914&oauth_token=12977829338e5f953e3d24bcef502b6a&track_deviceid=866479023806507&track_device_info=x600&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18&id=" + baskdetails_ID + "&trace_id=";

        try {
            HttpUtils.doPostAsyn(urlBaskDetails, paramsBaskDetails, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_BaskDetails = new Gson();
                    baskDetailsData = gson_BaskDetails.fromJson(result, BaskDetailsData.class);
                    if (baskDetailsData.getData() != null) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    BaskDetailsData.DataBean.PostBean.BrandProductBean brandP = baskDetailsData.getData().getPost().getBrand_product().get(0);

                    Picasso.with(BaskDetailsActivity.this).load(baskDetailsData.getData().getPost().getAuthor().getAvatar()).into(logo);
                    name.setText(baskDetailsData.getData().getPost().getAuthor().getNickname());

                    for (int i = 0; i < baskDetailsData.getData().getPost().getPics().size(); i++) {
                        ImageView imageviewBig = new ImageView(BaskDetailsActivity.this);
                        ImageOptions imageOptions = new ImageOptions.Builder()
                                .setSize(DensityUtil.dip2px(400), DensityUtil.dip2px(400))//图片大小
                                //.setRadius(DensityUtil.dip2px(5))//ImageView圆角半径
                                .setCrop(true)// 如果ImageView的大小不是定义为wrap_content, 不要crop.
                                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                                .setLoadingDrawableId(R.mipmap.ic_launcher)//加载中默认显示图片
                                .setFailureDrawableId(R.mipmap.ic_launcher)//加载失败后默认显示图片
                                .build();
                        imageviewBig.setPadding(0, 0, 0, 15);
                        x.image().bind(imageviewBig, baskDetailsData.getData().getPost().getPics().get(i).getUrl(), imageOptions);
                        lltImageBig.addView(imageviewBig);
                    }
                    content.setText(baskDetailsData.getData().getPost().getContent());
                    likes.setText(baskDetailsData.getData().getPost().getDynamic().getLikes() + " 人喜欢");
                    Picasso.with(BaskDetailsActivity.this).load(brandP.getPic()).into(iv_shop);
                    tv_title1.setText(brandP.getBrand().getName());
                    item_name.setText(brandP.getTitle());
                    price.setText(brandP.getPrice());
                    likes_tv.setText("喜欢");
                    //评论

                    //获取评论数，并转为 INT型
                    int conents = Integer.parseInt(baskDetailsData.getData().getPost().getDynamic().getComments());

                    if (conents > 0) {//判断conents，是否大于0。大于0，显示
                        comments.setVisibility(View.VISIBLE);
                        comments.setText("查看 全部" + baskDetailsData.getData().getPost().getDynamic().getComments() + "条评论");
                        baskCommentAdapter = new BaskCommentAdapter(BaskDetailsActivity.this,
                                baskDetailsData.getData().getPost().getComments(),
                                baskDetailsData.getData().getPost().getId());
                        comments_ScRecyclerView.setAdapter(baskCommentAdapter);
                        comments_ScRecyclerView.setLayoutManager(new FullyLinearLayoutManager(BaskDetailsActivity.this));
                    }


                    break;
            }
        }
    };

    private void initEvent() {

        back.setOnClickListener(this);
        logo.setOnClickListener(this);
        name.setOnClickListener(this);
        attention.setOnClickListener(this);
        re.setOnClickListener(this);
        rltLikes.setOnClickListener(this);
        comments.setOnClickListener(this);
        lltFoot.setOnClickListener(this);
        lltShop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            //返回上一个页面
            case R.id.back_act_baskdetails:
                finish();
                break;

            //作者介绍 页面
            case R.id.logo_act_baskdetails:
            case R.id.name_act_baskdetails:
                String author_ID = baskDetailsData.getData().getPost().getAuthor_id();
                Intent intent = new Intent(BaskDetailsActivity.this, OriginalAuthorActivity.class);
                editor.putString("author_iD", author_ID);
                editor.commit();
                startActivity(intent);
                break;

            //关注，点击后 背景变为灰色，同时变为已关注..作者介绍页面“粉丝数”+1，，二次点击后再—1
            case R.id.attention_act_baskdetails:
                if (flag == 0) {
                    Toast.makeText(this, "关注成功", Toast.LENGTH_SHORT).show();
                    attention.setText("已关注");
                    attention.setBackgroundColor(Color.GRAY);
                    flag = 1;
                } else {
                    attention.setText("+ 关注");
                    attention.setBackgroundColor(Color.RED);
                    flag = 0;
                }
                break;

            //跳转至 单品详情页面
            case R.id.re_sife_second_view_one:
                String shop_ID = baskDetailsData.getData().getPost().getRelation_id();
                Intent intent1 = new Intent(BaskDetailsActivity.this, ShopDetailsActivity.class);
                intent1.putExtra("shop_iD", shop_ID);
                startActivity(intent1);
                break;

            //点击后，切换视图，并Toast，二次点击，弹出Dialog
            case R.id.rltLikes_sife_second_view_one:
                if (flag == 0) {
                    likes_iv.setVisibility(View.GONE);
                    likes_tv.setVisibility(View.GONE);
                    imageview.setVisibility(View.VISIBLE);
                    textView.setVisibility(View.VISIBLE);
                    toastUtils.toast(baskDetailsData.getData().getPost().getBrand_product().get(0).getPic(), 1000);
                    flag = 1;
                } else {

                    dialogUtils.dialog(baskDetailsData.getData()
                            .getPost().getBrand_product().get(0).getPic(), onClickListener);
                }
                break;

            //跳转至 评论页面
            case R.id.comments_act_baskdetails:
                String comments_ID = baskDetailsData.getData().getPost().getId();
                Intent intent2 = new Intent(BaskDetailsActivity.this, CommentsActivity.class);
                intent2.putExtra("comments_iD", comments_ID);
                startActivity(intent2);

                break;

            //底部“我来说两句”，点击后，改变视图
            case R.id.lltFoot_act_baskdetails:
            break;

            //购买，，跳到商城网站
            case R.id.lltShop_sife_second_view_one:

                String urlStore=baskDetailsData.getData().getPost().getBrand_product().get(0).getUrl();
                Uri uriStore=Uri.parse(urlStore);
                Intent intent3=new Intent(Intent.ACTION_VIEW,uriStore);
                startActivity(intent3);
            break;


        }
    }


    //回调接口，监听Dialog
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                //退出Dialog，在Activity中写取消喜欢
                case R.id.cancel_likes_wish_dialog:
                    dialogUtils.cancelBtn();
                    likes_iv.setVisibility(View.VISIBLE);
                    likes_tv.setVisibility(View.VISIBLE);
                    imageview.setVisibility(View.GONE);
                    textView.setVisibility(View.GONE);
                    flag = 0;
                    break;

                //退出Dialog
                case R.id.bad_likes_wish_dialog:
                    dialogUtils.badIma();
                    break;

                //退出Dialog，并Toast
                case R.id.lltLike_likes_wish_dialog:
                    toastUtils.toast(baskDetailsData.getData().getPost().getBrand_product().get(0).getPic(), 1000);
                    dialogUtils.lltLike();
                    break;

                //跳转至，编辑心愿单页面
                case R.id.found_likes_wish_dialog:
                    //跳转Activity，已封装在自定义Dialog中
//                    Intent intent = new Intent(BaskDetailsActivity.this, EditorWishActivity.class);
//                    startActivity(intent);
                    dialogUtils.found();
                    break;
            }
        }
    };
}
